/**
 * WebSocket管理 Composable
 */
import { ref, onMounted, onUnmounted } from 'vue'

export function useWebSocket() {
  // 响应式数据
  const wsConnected = ref(false)
  const wsRetryCount = ref(0)
  const maxRetries = 3
  let socketTask = null
  let reconnectTimer = null

  // 方法
  const connectWebSocket = () => {
    try {
      const token = uni.getStorageSync('accessToken')
      if (!token) {
        console.log('无访问令牌，跳过 WebSocket 连接')
        return
      }

      console.log('建立 WebSocket 连接...')
      
      socketTask = uni.connectSocket({
        url: `wss://${NETWORK_CONFIG.API_BASE_URL}/api/?accessToken=${token}`,
        success: () => {
          console.log('WebSocket 连接请求已发送')
          wsConnected.value = true
        },
        fail: (error) => {
          console.error('WebSocket 连接失败:', error)
          handleWebSocketError(error)
        }
      })

      // 监听连接状态
      uni.onSocketOpen(() => {
        console.log('WebSocket 连接已打开')
        wsConnected.value = true
        wsRetryCount.value = 0
      })

      uni.onSocketError((error) => {
        console.error('WebSocket 发生错误:', error)
        wsConnected.value = false
        handleWebSocketError(error)
      })

      uni.onSocketClose(() => {
        console.log('WebSocket 连接已关闭')
        wsConnected.value = false
        handleReconnection()
      })

      uni.onSocketMessage((res) => {
        handleWebSocketMessage(res.data)
      })

    } catch (error) {
      console.error('WebSocket 连接初始化失败:', error)
    }
  }

  const handleWebSocketError = (error) => {
    if (wsRetryCount.value < maxRetries) {
      console.log(`WebSocket 连接失败，5 秒后进行第 ${wsRetryCount.value + 1} 次重试`)
      reconnectTimer = setTimeout(() => {
        wsRetryCount.value++
        connectWebSocket()
      }, 5000)
    } else {
      console.log('WebSocket 重试次数已达上限，停止重连')
      uni.showToast({
        title: '网络连接异常，部分功能可能受限',
        icon: 'none',
        duration: 3000
      })
    }
  }

  const handleReconnection = () => {
    if (wsRetryCount.value < maxRetries) {
      reconnectTimer = setTimeout(() => {
        wsRetryCount.value++
        connectWebSocket()
      }, 5000)
    }
  }

  const handleWebSocketMessage = (data) => {
    try {
      console.log('收到 WebSocket 消息:', data)
      
      const message = JSON.parse(data)
      
      // 消息去重
      if (message.id) {
        const messageKey = `processed_${message.id}`
        if (uni.getStorageSync(messageKey)) {
          console.log('消息已处理过，跳过:', message.id)
          return
        }
        uni.setStorageSync(messageKey, true)
        setTimeout(() => {
          uni.removeStorageSync(messageKey)
        }, 5 * 60 * 1000)
      }

      // 处理不同类型的消息
      switch (message.type) {
        case 'task-progress':
          console.log('收到任务进度更新:', message)
          uni.$emit('task-progress-update', message)
          break
          
        case 'chatmessage':
          console.log('收到聊天消息:', message)
          uni.$emit('chatMessage', message)
          break
          
        case 'message':
          console.log('收到通知消息:', message)
          uni.$emit('notification', message)
          break
          
        case 'message_sent':
          console.log('收到消息发送确认:', message)
          uni.$emit('message-sent', message)
          break
          
        case 'team-update':
          console.log('收到团队更新:', message)
          uni.$emit('team-update', message)
          break
          
        case 'vote-update':
          console.log('收到投票更新:', message)
          uni.$emit('vote-update', message)
          break
          
        default:
          console.log('未知消息类型:', message.type)
      }
    } catch (error) {
      console.error('处理 WebSocket 消息失败:', error)
    }
  }

  const sendMessage = (message) => {
    if (socketTask && wsConnected.value) {
      try {
        socketTask.send({
          data: JSON.stringify(message)
        })
        console.log('发送 WebSocket 消息:', message)
      } catch (error) {
        console.error('发送 WebSocket 消息失败:', error)
      }
    } else {
      console.warn('WebSocket 未连接，无法发送消息')
    }
  }

  const disconnect = () => {
    if (socketTask) {
      socketTask.close()
      socketTask = null
    }
    if (reconnectTimer) {
      clearTimeout(reconnectTimer)
      reconnectTimer = null
    }
    wsConnected.value = false
    wsRetryCount.value = 0
  }

  // 生命周期
  onMounted(() => {
    connectWebSocket()
  })

  onUnmounted(() => {
    disconnect()
  })

  return {
    // 响应式数据
    wsConnected,
    wsRetryCount,
    
    // 方法
    connectWebSocket,
    disconnect,
    sendMessage,
    handleWebSocketMessage
  }
}
